import React, { useState, useEffect } from 'react';
import { printerApi, SystemPrinter } from '../../services/printerApi';
import './style.css';

interface ScanPrinterDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onScanComplete: (selectedPrinters: any[]) => void;
}

const isValidIP = (ip: string): boolean => {
  const parts = ip.split('.');
  if (parts.length !== 4) return false;
  
  return parts.every(part => {
    const num = parseInt(part, 10);
    return !isNaN(num) && num >= 0 && num <= 255;
  });
};

const ScanPrinterDialog: React.FC<ScanPrinterDialogProps> = ({
  isOpen,
  onClose,
  onScanComplete
}) => {
  const [startIP, setStartIP] = useState('');
  const [endIP, setEndIP] = useState('');
  const [scanning, setScanning] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [foundPrinters, setFoundPrinters] = useState<any[]>([]);
  const [selectedPrinters, setSelectedPrinters] = useState<Set<number>>(new Set());
  const [scanMode, setScanMode] = useState<'network' | 'system'>('system');
  const [systemPrinters, setSystemPrinters] = useState<SystemPrinter[]>([]);
  const [loadingSystemPrinters, setLoadingSystemPrinters] = useState(false);
  const [syncingPrinters, setSyncingPrinters] = useState(false);

  // 加载系统打印机
  useEffect(() => {
    if (isOpen && scanMode === 'system') {
      fetchSystemPrinters();
    }
  }, [isOpen, scanMode]);

  useEffect(() => {
    if (isOpen && scanMode === 'system') {
      syncSystemPrinters();
    }
  }, [isOpen, scanMode]);

  const fetchSystemPrinters = async () => {
    try {
      setLoadingSystemPrinters(true);
      setError(null);
      
      // 使用新的统一API获取所有打印机
      const response = await printerApi.getAllPrinters();
      const allPrinters = response.printers || [];
      
      // 过滤出系统打印机
      const systemPrinters = allPrinters.filter(printer => printer.isSystem || (printer as any).isSystemPrinter);
      
      // 兼容旧接口
      const legacySystemPrinters = systemPrinters.map(printer => ({
        name: printer.name,
        driverName: (printer as any).driverName || '系统打印机',
        portName: (printer as any).portName || (printer as any).ip || '',
        status: (printer as any).status || 0,
        statusText: (printer as any).statusText || '可用',
        isReady: (printer as any).isReady || (printer as any).isOnline || true
      }));
      
      setSystemPrinters(legacySystemPrinters);
      
      // 将系统打印机映射到与网络打印机格式一致的格式
      const mappedPrinters = legacySystemPrinters.map(printer => ({
        name: printer.name,
        ip: printer.portName,
        port: 9100,
        protocol: 'RAW',
        description: `驱动: ${printer.driverName}`,
        isOnline: printer.isReady,
        status: printer.statusText
      }));

      setFoundPrinters(mappedPrinters);
      console.log('找到系统打印机:', mappedPrinters.length, '台');
      
      if (mappedPrinters.length === 0) {
        setError('未发现系统打印机，请检查打印机连接或手动添加');
      }
    } catch (err: any) {
      console.error('获取系统打印机失败:', err);
      setError(err.message || '获取系统打印机失败');
    } finally {
      setLoadingSystemPrinters(false);
    }
  };

  // 同步系统打印机到数据库
  const syncSystemPrinters = async () => {
    try {
      setSyncingPrinters(true);
      setError(null);
      console.log('开始同步系统打印机');
      
      const result = await printerApi.syncSystemPrinters();
      console.log('同步系统打印机完成:', result);
      
      if (result.success && result.printers) {
        // 直接使用从API返回的打印机列表
        const syncedPrinters = result.printers.map(printer => ({
          name: printer.name,
          ip: printer.ip,
          port: printer.port,
          protocol: printer.protocol,
          description: printer.description,
          isOnline: printer.isOnline,
          isSystemPrinter: printer.isSystemPrinter
        }));
        
        setFoundPrinters(syncedPrinters);
        console.log('设置找到的打印机:', syncedPrinters);
        
        // 自动选择所有同步的打印机
        const newSelectedPrinters = new Set<number>();
        for (let i = 0; i < syncedPrinters.length; i++) {
          newSelectedPrinters.add(i);
        }
        setSelectedPrinters(newSelectedPrinters);
        console.log('自动选择所有同步的打印机:', newSelectedPrinters);
      } else {
        setError('同步系统打印机失败: ' + (result.message || '未知错误'));
      }
    } catch (err: any) {
      console.error('同步系统打印机失败:', err);
      setError('同步系统打印机失败: ' + (
        err.response?.data?.message || 
        err.message || 
        '未知错误'
      ));
    } finally {
      setSyncingPrinters(false);
    }
  };

  const validateIPRange = (start: string, end: string): string | null => {
    if (!isValidIP(start)) {
      return '起始IP地址格式不正确';
    }
    if (!isValidIP(end)) {
      return '结束IP地址格式不正确';
    }

    const startParts = start.split('.').map(Number);
    const endParts = end.split('.').map(Number);

    // 确保在同一网段
    if (startParts[0] !== endParts[0] || 
        startParts[1] !== endParts[1] || 
        startParts[2] !== endParts[2]) {
      return '起始IP和结束IP必须在同一网段';
    }

    // 检查IP范围
    const startNum = startParts[3];
    const endNum = endParts[3];
    if (startNum > endNum) {
      return '起始IP必须小于或等于结束IP';
    }
    if (endNum - startNum > 255) {
      return 'IP范围不能超过255个地址';
    }

    return null;
  };

  const handleStartScan = async () => {
    const validationError = validateIPRange(startIP, endIP);
    if (validationError) {
      console.log('IP验证失败:', validationError);
      setError(validationError);
      return;
    }

    try {
      setScanning(true);
      setError(null);
      console.log('开始扫描IP范围:', {
        startIP,
        endIP,
        timestamp: new Date().toISOString()
      });

      const result = await printerApi.scanPrinters(startIP, endIP);
      
      console.log('扫描完成，原始响应:', {
        result,
        timestamp: new Date().toISOString()
      });

      if (!result) {
        console.error('扫描结果为空');
        setError('扫描失败，未收到有效响应');
        return;
      }

      if (!Array.isArray(result.printers)) {
        console.error('扫描结果格式错误:', result);
        setError('扫描结果格式错误');
        return;
      }

      console.log('发现打印机数量:', result.printers.length);
      result.printers.forEach((printer, index) => {
        console.log(`打印机 ${index + 1}:`, {
          ip: printer.ip,
          port: printer.port,
          protocol: printer.protocol,
          name: printer.name,
          details: printer
        });
      });

      setFoundPrinters(result.printers);
      
      if (result.printers.length === 0) {
        console.log('未发现打印机');
        setError('未发现打印机，请检查IP范围或确保打印机已开启');
      } else {
        console.log('扫描成功，发现打印机:', result.printers.length, '台');
      }
    } catch (err: any) {
      console.error('扫描出错:', {
        error: err,
        message: err.message,
        response: err.response,
        timestamp: new Date().toISOString()
      });

      // 详细的错误信息
      if (err.response) {
        console.error('服务器响应:', {
          status: err.response.status,
          statusText: err.response.statusText,
          data: err.response.data
        });
      }

      if (err.request) {
        console.error('请求详情:', {
          method: err.request.method,
          url: err.request.url,
          headers: err.request.headers
        });
      }

      setError(
        err.response?.data?.message || 
        err.message || 
        '扫描失败，请重试'
      );
    } finally {
      console.log('扫描流程结束');
      setScanning(false);
    }
  };

  const handleToggleSelect = (index: number) => {
    const newSelected = new Set(selectedPrinters);
    if (newSelected.has(index)) {
      newSelected.delete(index);
    } else {
      newSelected.add(index);
    }
    setSelectedPrinters(newSelected);
  };

  const handleConfirm = () => {
    const selectedPrintersList = Array.from(selectedPrinters).map(index => foundPrinters[index]);
    onScanComplete(selectedPrintersList);
    handleClose();
  };

  const handleClose = () => {
    setStartIP('');
    setEndIP('');
    setFoundPrinters([]);
    setSelectedPrinters(new Set());
    setError(null);
    onClose();
  };

  const handleQuickScan = () => {
    const parts = startIP.split('.');
    if (parts.length === 4) {
      setEndIP(`${parts[0]}.${parts[1]}.${parts[2]}.255`);
    }
  };

  const handleSingleIP = () => {
    setEndIP(startIP);
  };

  const handleSwitchMode = (mode: 'network' | 'system') => {
    setScanMode(mode);
    if (mode === 'system') {
      fetchSystemPrinters();
    } else {
      setFoundPrinters([]);
      setSelectedPrinters(new Set());
    }
  };

  if (!isOpen) return null;

  return (
    <div className="scan-dialog-overlay">
      <div className="scan-dialog">
        <div className="scan-dialog-header">
          <h2>添加打印机</h2>
          <button className="btn-close" onClick={handleClose}>
            <i className="fas fa-times"></i>
          </button>
        </div>

        <div className="scan-mode-selector">
          <button 
            className={`mode-button ${scanMode === 'system' ? 'active' : ''}`} 
            onClick={() => handleSwitchMode('system')}
          >
            系统打印机
          </button>
          <button 
            className={`mode-button ${scanMode === 'network' ? 'active' : ''}`} 
            onClick={() => handleSwitchMode('network')}
          >
            网络扫描
          </button>
        </div>

        <div className="scan-dialog-content">
          {scanMode === 'network' ? (
            <div className="ip-range-inputs">
              <div className="form-group">
                <label>起始IP</label>
                <input
                  type="text"
                  value={startIP}
                  onChange={(e) => {
                    setStartIP(e.target.value);
                    setError(null);
                  }}
                  placeholder="例如: 192.168.1.1"
                  disabled={scanning}
                />
                <div className="quick-actions">
                  <button 
                    className="btn btn-text" 
                    onClick={handleQuickScan}
                    disabled={!startIP || scanning}
                  >
                    扫描整个网段
                  </button>
                  <button 
                    className="btn btn-text" 
                    onClick={handleSingleIP}
                    disabled={!startIP || scanning}
                  >
                    扫描单个IP
                  </button>
                </div>
              </div>
              <div className="form-group">
                <label>结束IP</label>
                <input
                  type="text"
                  value={endIP}
                  onChange={(e) => {
                    setEndIP(e.target.value);
                    setError(null);
                  }}
                  placeholder="例如: 192.168.1.255"
                  disabled={scanning}
                />
              </div>
              <div className="scan-actions">
                <button 
                  className="btn btn-primary" 
                  onClick={handleStartScan}
                  disabled={!startIP || !endIP || scanning}
                >
                  {scanning ? '扫描中...' : '开始扫描'}
                </button>
              </div>
            </div>
          ) : (
            <div className="system-printers-section">
              <div className="refresh-container">
                <button 
                  className="btn btn-primary refresh-button" 
                  onClick={fetchSystemPrinters}
                  disabled={loadingSystemPrinters || syncingPrinters}
                >
                  {loadingSystemPrinters ? '加载中...' : '刷新系统打印机'}
                </button>
                <button 
                  className="btn btn-primary sync-button" 
                  onClick={syncSystemPrinters}
                  disabled={loadingSystemPrinters || syncingPrinters}
                >
                  {syncingPrinters ? '同步中...' : '同步系统打印机到数据库'}
                </button>
              </div>
              <div className="sync-hint">
                注意: 同步操作会清空数据库中的打印机列表，并添加当前系统中的打印机
              </div>
            </div>
          )}

          {error && <div className="error-message">{error}</div>}

          {(scanning || loadingSystemPrinters || syncingPrinters) ? (
            <div className="scanning-status">
              <div className="spinner"></div>
              <p>
                {scanMode === 'network' 
                  ? '正在扫描...' 
                  : syncingPrinters 
                    ? '正在同步系统打印机到数据库...' 
                    : '正在加载系统打印机...'}
              </p>
            </div>
          ) : foundPrinters.length > 0 ? (
            <div className="printer-list">
              <div className="printer-list-header">
                <h3>{scanMode === 'network' ? '发现的打印机' : '系统打印机'}</h3>
                <span>已选择 {selectedPrinters.size} 台</span>
              </div>
              {foundPrinters.map((printer, index) => (
                <div
                  key={index}
                  className={`printer-item ${selectedPrinters.has(index) ? 'selected' : ''}`}
                  onClick={() => handleToggleSelect(index)}
                >
                  <div className="printer-info">
                    <div className="printer-name">{printer.name || `打印机 (${printer.ip})`}</div>
                    <div className="printer-details">
                      {scanMode === 'network' ? (
                        <>
                          <span>IP: {printer.ip}</span>
                          <span>端口: {printer.port}</span>
                          <span>协议: {printer.protocol}</span>
                        </>
                      ) : (
                        <>
                          <span>端口: {printer.ip}</span>
                          <span>状态: {printer.status}</span>
                          <span>描述: {printer.description}</span>
                        </>
                      )}
                    </div>
                  </div>
                  <div className="select-indicator">
                    <i className={`fas ${selectedPrinters.has(index) ? 'fa-check-circle' : 'fa-circle'}`}></i>
                  </div>
                </div>
              ))}
            </div>
          ) : null}
        </div>

        <div className="scan-dialog-footer">
          <button className="btn btn-secondary" onClick={handleClose}>
            取消
          </button>
          <button 
            className="btn btn-primary" 
            onClick={handleConfirm}
            disabled={selectedPrinters.size === 0}
          >
            添加选中的打印机
          </button>
        </div>
      </div>
    </div>
  );
};

export default ScanPrinterDialog; 